package com.bdqn.t362.common.servlet;

import com.bdqn.t362.common.utils.JedisUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lqm
 * @ClassName RoleFilter
 * @description: TODO
 */
@WebFilter(filterName = "RoleFilter", urlPatterns = "/*")
public class RoleFilter implements Filter {
    public void destroy() {
    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//        System.out.println("进入RoleFilter过滤器");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        String pathStr = request.getRequestURI();

        boolean isChain=false;
        if (pathStr.endsWith(".js") || pathStr.endsWith(".css")
                || pathStr.endsWith(".jpg") || pathStr.endsWith("login.jsp")
                || pathStr.endsWith(".png") || pathStr.contains("AdminLoginServlet")|| pathStr.contains("LoginSuccessServlet")) {
            isChain=true;
        } else {
            //验证是否登录
           ;

//            HttpSession session = request.getSession();
//            if (session.getAttribute("userEntity") != null) {
//                isChain=true;
//            }
            String tokenStr="";
            Cookie[] cookies=request.getCookies();
            if(cookies!=null){

                for (int i =0 ; i <cookies.length; i++){
                    if(cookies[i].getName().equals("userToken")){
                        tokenStr=cookies[i].getValue();
                    }
                }


                if (JedisUtils.getString(tokenStr) != null) {
                    isChain=true;
                }
            }
        }
        System.out.println(pathStr+"="+isChain);
        if(isChain){
            chain.doFilter(req, resp);
        }else{
            response.sendRedirect(request.getContextPath() + "/bsadmin/login.jsp");
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
